package com.jianhua.appmarket.module.service.system.impl;

import com.jianhua.appmarket.common.util.AssertBusiness;
import com.jianhua.appmarket.common.util.SnowflakeKeyUtil;
import com.jianhua.appmarket.module.dao.system.RoleMenuDao;
import com.jianhua.appmarket.module.entity.system.RoleMenu;
import com.jianhua.appmarket.module.model.system.RoleMenuParam;
import com.jianhua.appmarket.module.model.system.UserVO;
import com.jianhua.appmarket.module.service.system.IRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class RoleMenuService implements IRoleMenuService {

    @Autowired
    private RoleMenuDao roleMenuDao;

    @Override
    public List<RoleMenu> listByRoleId(Long roleId) {
        RoleMenu param = new RoleMenu();
        param.setRoleId(roleId);
        return roleMenuDao.listByParam(param);
    }


    @Override
    @Transactional
    public Boolean saveRoleMenus(RoleMenuParam roleMenuParam, UserVO user) throws Exception {
        Long roleId = roleMenuParam.getRoleId();
        AssertBusiness.isTrue(0 <= roleId,"请先选择一个角色!");

        //先删除再添加
        RoleMenu deleteParam = new RoleMenu();
        deleteParam.setRoleId(roleId);
        roleMenuDao.deleteByParam(deleteParam);

        RoleMenu roleMenu =new RoleMenu();
        for(Long menuId : roleMenuParam.getMenuIds()){
            roleMenu.setId(SnowflakeKeyUtil.generateId());
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenu.setCreateUser(user.getNickName());
            roleMenu.setUpdateUser(user.getNickName());
            roleMenu.setUpdateTime(new Date());
            roleMenuDao.insert(roleMenu);
        }
        return Boolean.TRUE;
    }
}
